// src/services/fileService.ts
import api from './api';
import RNFS from 'react-native-fs';
import { Platform } from 'react-native';

interface FileUploadResponse {
  url: string;
  fileName: string;
  size: number;
  type: string;
}

interface FileInfo {
  uri: string;
  name: string;
  type: string;
  size?: number;
}

class FileService {
  // 上传图片
  async uploadImage(imagePath: string, onProgress?: (progress: number) => void): Promise<string> {
    const formData = new FormData();
    const fileName = imagePath.split('/').pop() || `image_${Date.now()}.jpg`;

    formData.append('file', {
      uri: imagePath,
      name: fileName,
      type: 'image/jpeg',
    } as any);

    const response = await api.upload<FileUploadResponse>(
      '/api/file/upload/image',
      formData,
      onProgress
    );

    return response.data.url;
  }

  // 上传音频
  async uploadAudio(audioPath: string, onProgress?: (progress: number) => void): Promise<string> {
    const formData = new FormData();
    const fileName = audioPath.split('/').pop() || `audio_${Date.now()}.mp3`;

    formData.append('file', {
      uri: audioPath,
      name: fileName,
      type: 'audio/mpeg',
    } as any);

    const response = await api.upload<FileUploadResponse>(
      '/api/file/upload/audio',
      formData,
      onProgress
    );

    return response.data.url;
  }

  // 批量上传
  async uploadMultiple(files: FileInfo[], onProgress?: (progress: number) => void): Promise<string[]> {
    const formData = new FormData();

    files.forEach((file, index) => {
      formData.append('files', {
        uri: file.uri,
        name: file.name,
        type: file.type,
      } as any);
    });

    const response = await api.upload<{ urls: string[] }>(
      '/api/file/upload/multiple',
      formData,
      onProgress
    );

    return response.data.urls;
  }

  // 下载文件
  async downloadFile(url: string, fileName: string, onProgress?: (progress: number) => void): Promise<string> {
    const localPath = `${RNFS.DocumentDirectoryPath}/${fileName}`;

    const downloadResult = await RNFS.downloadFile({
      fromUrl: url,
      toFile: localPath,
      progress: (res) => {
        if (onProgress) {
          const progress = Math.round((res.bytesWritten / res.contentLength) * 100);
          onProgress(progress);
        }
      },
    }).promise;

    if (downloadResult.statusCode === 200) {
      return localPath;
    } else {
      throw new Error(`Download failed with status: ${downloadResult.statusCode}`);
    }
  }

  // 删除文件
  async deleteFile(fileUrl: string): Promise<void> {
    await api.delete('/api/file/delete', {
      params: { url: fileUrl },
    });
  }

  // 获取文件信息
  async getFileInfo(fileUrl: string): Promise<FileUploadResponse> {
    const response = await api.get<FileUploadResponse>('/api/file/info', {
      params: { url: fileUrl },
    });
    return response.data;
  }

  // 压缩图片
  async compressImage(imagePath: string, quality = 0.8): Promise<string> {
    // 这里可以使用 react-native-image-resizer 库进行图片压缩
    // 示例代码
    return imagePath;
  }

  // 获取文件大小
  async getFileSize(filePath: string): Promise<number> {
    const stat = await RNFS.stat(filePath);
    return stat.size;
  }

  // 检查文件是否存在
  async fileExists(filePath: string): Promise<boolean> {
    return await RNFS.exists(filePath);
  }

  // 创建目录
  async createDirectory(dirPath: string): Promise<void> {
    const exists = await RNFS.exists(dirPath);
    if (!exists) {
      await RNFS.mkdir(dirPath);
    }
  }

  // 获取缓存目录
  getCacheDirectory(): string {
    return Platform.OS === 'ios'
      ? RNFS.CachesDirectoryPath
      : RNFS.ExternalCachesDirectoryPath;
  }

  // 清除缓存
  async clearCache(): Promise<void> {
    const cacheDir = this.getCacheDirectory();
    const files = await RNFS.readDir(cacheDir);

    await Promise.all(
      files.map(file => RNFS.unlink(file.path))
    );
  }

  // 获取缓存大小
  async getCacheSize(): Promise<number> {
    const cacheDir = this.getCacheDirectory();
    const files = await RNFS.readDir(cacheDir);

    let totalSize = 0;
    for (const file of files) {
      totalSize += file.size;
    }

    return totalSize;
  }
}

export default new FileService();